// const {slugify} = require('transliteration');
// const md5 = require("md5");
const svgCaptcha = require("svg-captcha");

module.exports = class extends think.Controller {


    async loginAction() {

        if (this.isPost) {
            // if (this.session.verify != data.verify.toLowerCase()) {
            //     this.redirect('/admin/public/login?err=' + encodeURI('验证码错误'));
            //     return;
            // }
            const username = this.post('username');
            const password = think.md5(this.post('password'));
            let Administrator = this.mongoose('Administrator', {}, 'admin');

            // let admin = await Administrator.findOne({username: username, password: password, status: 1}).lean().exec();
            let admin = await Administrator.findOne({username: username, password: password}).lean().exec();

            // console.log(admin);

            // if (admin && admin.status===1) {
            if (admin) {
                await this.session('adminId', admin._id.toString());//admin._id的虚拟属性
                await this.session('adminUsername', admin.username);

                // const secret = koahub.configs['middleware']['koahub-jwt']['secret'];
                // // koahub.logger.debug(secret);
                //
                // const jwt = require('jsonwebtoken');
                // const token = jwt.sign({
                //     data: admin.id,
                //     // 设置 token 过期时间
                //     exp: Math.floor(Date.now() / 1000) + (60 * 60), // 60 seconds * 60 minutes = 1 hour
                // }, secret);
                // this.session.token = token;


                this.success('/admin/index/index','登录成功');
            } else {
                this.fail(1001,'账号密码错误');
            }

        } else {
            await this.display('admin/public/login');
        }
    }

    async verifyAction() {

        const captcha = svgCaptcha.create();

        this.session('verify', captcha.text.toLowerCase());
        this.header('Content-Type', 'image/svg+xml');
        this.ctx.body = captcha.data;
    }

    async logoutAction() {
        await this.session(null);
        this.redirect('/admin/public/login');
    }

};